package com.dq.health.utils.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Set;

/**
 * 树类
 * 
 * @author *
 * @param <T>
 */
public class Tree<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = LoggerFactory.getLogger(Tree.class);

	private Node<T> root;

	public Node<T> getRoot() {
		return root;
	}

	public Tree() {

	}

	public Tree(Node<T> root) {
		super();
		this.root = root;
	}

	public Tree(T rootData) {
		super();

		Node<T> node = new Node<T>();
		node.setData(rootData);
		this.root = node;
	}

	/**
	 * 增加新节点
	 * 
	 * @param curNode
	 * @param newNode
	 */
	public void addNewNode(Node<T> curNode, Node<T> newNode) {
		if (newNode == null || curNode == null) {
			return;
		}

		newNode.setParentNodeIds(curNode.getParentNodeIds());
		curNode.addChildNode(newNode);
	}

	/**
	 * 遍历
	 */
	public void traversal(Node<T> root) {
		for (Node<T> tempNode : root.getChildren()) {
			traversal(tempNode);
		}
	}

	/**
	 * 查找
	 * 
	 * @param root
	 * @param searchcont
	 * @return
	 */
	private void searchHelp(Node<T> root, Node<T> result, String nodeId) {
		if (root.getNodeId().equals(nodeId)) {
			result.setData(root.getData());
			result.setChildren(root.getChildren());
			result.setParentNodeIds(root.getParentNodeIds());
			return;
		}

		for (Node<T> tempNode : root.getChildren()) {
			LOGGER.info(tempNode.getNodeId());
			searchHelp(tempNode, result, nodeId);
		}
	}

	public Node<T> search(Node<T> root, String nodeId) {
		if (nodeId == null || nodeId.trim().length() == 0) {
			return null;
		}
		Node<T> result = new Node<T>();
		searchHelp(root, result, nodeId);
		return result;
	}

	public Tree<T> getChildTree(String nodeId) {
		Node<T> search = search(this.root, nodeId);
		Set<Node<T>> childNodes = search.getChildren();
		for (Node<T> node : childNodes) {
			node.getChildren().clear();
			node.getParentNodeIds().clear();
		}
		return TreeUtil.make(childNodes);
	}
}
